package cn.ztydata.teachingsystem.heaven.service;

import cn.ztydata.teachingsystem.common.Page;
import cn.ztydata.teachingsystem.exception.ServiceException;
import cn.ztydata.teachingsystem.heaven.common.WebContext;
import cn.ztydata.teachingsystem.heaven.cons.GroupType;
import cn.ztydata.teachingsystem.heaven.cons.Roles;
import cn.ztydata.teachingsystem.heaven.dao.ClassGroupDao;
import cn.ztydata.teachingsystem.heaven.dao.CommentDao;
import cn.ztydata.teachingsystem.heaven.dao.CourseGroupDao;
import cn.ztydata.teachingsystem.heaven.dao.SpeakDao;
import cn.ztydata.teachingsystem.heaven.dao.redis.SpeakComCountDao;
import cn.ztydata.teachingsystem.heaven.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 发言业务类
 *
 * @author lyj
 * @since 2015-3-21
 */
@Service
public class SpeakService extends BaseService {
    @Autowired
    private SpeakDao speakDao;
    @Autowired
    private WebContext webContext;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private CommentDao commentDao;
    @Autowired
    private SpeakComCountDao speakComCountDao;
    @Autowired
    private CourseGroupDao courseGroupDao;
    @Autowired
    private ClassGroupDao classGroupDao;
    @Autowired
    private SpecialtyGroupService specialtyGroupService;

    //<editor-fold desc="验证">
    /**
     * 验证角色
     * @param groupType 群组类型
     * @return void
     * @author lyj
     * @since 2015-5-7
     */
    public void checkRole(final int groupType) {
        //角色验证
        Boolean checkRole = true;
        if (groupType == GroupType.CLASS_GROUP || groupType == GroupType.COURSE_GROUP) {
            if (webContext.getRole() != Roles.TEACHER && webContext.getRole() != Roles.STUDENT) {
                checkRole = false;
            }
        } else if (groupType == GroupType.SPEC_GROUP) {
            if (webContext.getRole() != Roles.SPEC_LEADER && webContext.getRole() != Roles.TEACHER) {
                checkRole = false;
            }
        }

        if (!checkRole){
            log.warn("当前登录用户没有权限使用该功能！");
            throw new ServiceException("权限错误！");
        }
    }



    /**
     * 验证权限
     *
     * @param speakId 发言ID
     * @param groupType 群组类型
     * @param number 登录用户工号或学号
     * @return boolean
     * @author lyj
     * @since 2015-3-26
     */
    public void checkCreator(final long speakId, final int groupType, final String number) {

        Boolean check = false;

        //判断登录用户是否为发言创建人
        if (speakDao.checkCreator(speakId) == 1) {
            log.debug("判断登录用户是否为发言创建人speakDao.checkCreator(speakId) == 1");
            check = true;
        }

        if (webContext.getRole() != Roles.STUDENT) {

            //判断发言所在群组是否为老师所管理的群组
            if (groupType == GroupType.COURSE_GROUP) { //验证课程群组
                if (speakDao.checkGroup(speakId) == 1) {
                    check = true;
                }
            } else if (groupType == GroupType.CLASS_GROUP) { //验证班级群组
                if (speakDao.checkClassGroup(speakId, number, groupType) == 1) {
                    check = true;
                }
            } else if (groupType == GroupType.SPEC_GROUP) { //验证专业群组
                if (speakDao.checkSpecGroup(speakId, groupType) == 1) {
                    check = true;
                }
            }
        }

        if (!check) {
            log.warn("当前登录用户没有权限使用该功能！");
            throw new ServiceException("权限错误或已经被删除！");
        }

    }
    //</editor-fold>

    //<editor-fold desc="新增">
    /**
     * 新增发言
     *
     * @param speak 发言实体
     * @return void
     * @author lyj
     * @since 2015-3-21
     */
    public void addSpeak(Speak speak) {
        //角色验证
        checkRole(speak.getGroupType());

        if (speakDao.addSpeak(speak) != 1) {
            log.debug("判断新增是否成功speakDao.addSpeak(speak) != 1");
            log.warn("新增发言失败！");

            throw new ServiceException("新增发言失败！");
        }
    }
    //</editor-fold>

    //<editor-fold desc="删除">
    /**
     * 删除发言
     *
     * @param id 发言ID
     * @return void
     * @author lyj
     * @since 2015-3-21
     */
    @Transactional
    public void deleteSpeak(final long id, final int groupType, final User userInfo){

        //角色验证
        checkRole(groupType);

        checkCreator(id, groupType, userInfo.getNumber());

        if (speakDao.deleteSpeak(id) != 1){
            log.debug("删除发言speakDao.deleteSpeak(id) != 1");
            log.warn("删除发言失败！");
            throw new ServiceException();
        }

        //删除发言回复
        commentDao.deleteBySpeakId(id);

    }
    //</editor-fold>

    //<editor-fold desc="查询">
    /**
     * 获取发言列表
     *
     * @param groupType 群组类型（0非群组 1课程群组 2专业群组 3班级群组）
     * @param groupId 群组ID
     * @param pageNum 当前页码
     * @param pageSize 每页条数
     * @param tag tag标记（0全部 1我的）
     * @return page
     * @author lyj
     * @since 2015-3-21
     */
    public Page<Speak> getList(final int groupType, final long groupId, final int pageNum, final int pageSize, final int tag, final User userInfo){

        //角色验证
        checkRole(groupType);

        //判断登录用户是否可以获取该课程群组信息
        if (groupType == GroupType.COURSE_GROUP) { //验证课程群组
            if (courseGroupDao.checkGroupIdIsNum(groupId, userInfo.getNumber()) == 0) {
                throw new ServiceException("权限错误！");
            }
        } else if (groupType == GroupType.CLASS_GROUP) { //验证班级群组

            //判断登录用户是否可以获取该班级群组信息
            if (classGroupDao.checkGroupIdIsNum(groupId, userInfo.getNumber()) == 0) {
                throw new ServiceException("权限错误！");
            }
        } else if (groupType == GroupType.SPEC_GROUP) { //验证专业群组

            //判断登录用户是否可以获取该专业群组信息
            if (!specialtyGroupService.getSpecialtyIds(userInfo).contains(groupId)) {
                throw new ServiceException("权限错误！");
            }
        }


        long creatorId = 0;
        if (tag == 1){
            log.debug("如果tag == 1");
            creatorId = webContext.getUserId();
        }

        Page<Speak> page = speakDao.getList(groupType, groupId, pageNum, pageSize, creatorId);

        //存储老师ID
        Set<Long> teacherIds = new HashSet<>();
        //存储学生ID
        Set<Long> studentIds = new HashSet<>();

        if (page.getItems().size() == 0){
            log.debug("page.getItems().size() == 0");
            return page;
        }

        //循环读取创建人ID
        log.debug("循环读取创建人ID");
        for (Speak speak : page.getItems()){
            if (speak.getRole() == 0){
                log.debug("speak.getRole() == 0");
                teacherIds.add(speak.getCreatorId());
            } else {
                log.debug("如果角色不为零");
                studentIds.add(speak.getCreatorId());
            }
        }

        //获取教师头像、姓名
        Map<Long, Teacher> reTeacher = teacherService.getPictures(teacherIds);
        //获取学生头像、姓名
        Map<Long, Student> reStudent = studentService.getPictures(studentIds);

        //循环绑定头像和姓名
        log.debug("循环绑定头像和姓名");
        for (Speak speak : page.getItems()){
            if (speak.getRole() == 0) {
                log.debug("1speak.getRole() == 0");
                speak.setCreatorName(reTeacher.get(speak.getCreatorId()).getName());
                speak.setCreatorPhoto(reTeacher.get(speak.getCreatorId()).getPicture());


            } else {
                log.debug("1如果角色不为零");
                speak.setCreatorName(reStudent.get(speak.getCreatorId()).getName());
                speak.setCreatorPhoto(reStudent.get(speak.getCreatorId()).getAvatar());
            }

            //获取回复数量
            speak.setCommentCount(speakComCountDao.getCount(speak.getId(), speakComCountDao.COMMENT_COUNT));
        }

        log.debug("获取发言列表");
        return page;
    }
    //</editor-fold>

}
